import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Form,
  Input,
  Button,
  message,
  Modal,
  InputNumber,
  Space,
  Radio,
  Row,
  Col,
  Table,
} from 'antd';
import { ExclamationCircleOutlined, PushpinOutlined } from '@ant-design/icons';
import { connect } from 'umi';

const currControl = 'Edu_BMI';
const { confirm } = Modal;
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      loading2: false,
      datas: {},
      pageIndex: 1,
      pageSize: 50,
      GrowthData: [],
      dataSource: [],
      sex: '1',
      btype: 1,
      age: 0,
    };
  }

  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchBMIData();
  }
  onFinish = async (values: any) => {
    this.setState({ loading2: true });
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.setState({ loading2: false });
          this.fetchBMIData();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  fetchDatas = (value: number) => {
    const { sex } = this.state;
    this.props
      .dispatch({
        type: 'Abp/getAll',
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp) {
          var datas = resp.result.items.filter((o: any) => o.age == value && o.sex == sex)[0];
          if (datas) {
            this.formRef.current.setFieldsValue({ model: datas });
            this.setState({ datas });
          } else {
            this.formRef.current.resetFields();
          }
        }
      });
  };
  fetchCurrent = (id: any) => {
    this.setState({ loading2: true });
    this.props
      .dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        console.log(resp);
        if (resp) {
          var datas = resp.result;
          if (datas) {
            this.formRef.current.setFieldsValue({ model: datas });
            this.setState({ datas, loading2: false });
          } else {
            this.formRef.current.resetFields();
          }
        }
      });
  };
  fetchBMIData = () => {
    const { sex } = this.state;
    this.setState({ loading: true });
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: { sex },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp) {
          var dataSource = resp.result.items;
          var totalCount = resp.result.totalCount;
          this.setState({ dataSource, loading: false, totalCount });
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.formRef.current.resetFields();
          this.fetchBMIData();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  CopyData = () => {
    let model = this.state.datas;
    model.id = undefined;
    model.age += 1;
    var act = 'Abp/create';
    this.props
      .dispatch({
        type: act,
        payload: model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('复制成功！');
          this.formRef.current.setFieldsValue({ model });
          this.fetchBMIData();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  g2LineBsc: any = React.createRef();
  onRef = (ref: any) => {
    this.g2LineBsc = ref;
  };
  handleSexChange = (e: any) => {
    let that = this;
    this.setState({ sex: e.target.value }, function () {
      that.fetchBMIData();
    });
  };
  render() {
    const { datas, loading, loading2, dataSource, sex, pageSize, totalCount } = this.state;
    const columns = [
      {
        title: '月龄',
        dataIndex: 'age',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        render: (text: number) => <span>{text == 0 ? '女' : '男'}</span>,
      },
      {
        title: '-3SD',
        dataIndex: 'sdB3',
      },
      {
        title: '-2SD',
        dataIndex: 'sdB2',
      },
      {
        title: '-1SD',
        dataIndex: 'sdB1',
      },
      {
        title: 'SD',
        dataIndex: 'sd',
      },
      {
        title: '+1SD',
        dataIndex: 'sD1',
      },
      {
        title: '+2SD',
        dataIndex: 'sD2',
      },
      {
        title: '+3SD',
        dataIndex: 'sD3',
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        this.fetchCurrent(selectedRowKeys);
      },
    };
    return (
      <PageHeaderWrapper>
        <Row gutter={[16, 16]}>
          <Col span={14}>
            <Card
              extra={
                <Radio.Group defaultValue={sex} value={sex} onChange={this.handleSexChange}>
                  <Radio.Button value="1">男孩</Radio.Button>
                  <Radio.Button value="0">女孩</Radio.Button>
                </Radio.Group>
              }
            >
              <Table
                rowKey="id"
                size="small"
                loading={loading}
                columns={columns}
                dataSource={dataSource}
                rowSelection={{
                  type: 'radio',
                  ...rowSelection,
                }}
                pagination={{
                  onChange: (page) => {
                    this.setState({ pageIndex: page }, () => {
                      this.fetchBMIData();
                    });
                  },
                  pageSize,
                  total: totalCount,
                }}
                onRow={(record) => {
                  return {
                    onClick: (event) => {},
                    onDoubleClick: (event) => {
                      this.fetchCurrent(record.id);
                    },
                  };
                }}
              />
            </Card>
          </Col>
          <Col span={10}>
            <Card>
              <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
                <Form.Item label="id" name={['model', 'id']} hidden>
                  <Input />
                </Form.Item>
                <Form.Item label="年龄" style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item
                      name={['model', 'age']}
                      rules={[{ required: true, message: '请输入年龄' }]}
                    >
                      <InputNumber onChange={(value: any) => this.setState({ age: value })} />
                    </Form.Item>
                    <Form.Item>
                      <Button
                        icon={<PushpinOutlined />}
                        onClick={() => this.fetchDatas(this.state.age)}
                      ></Button>
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item name={['model', 'sex']}>
                  <Radio.Group>
                    <Radio value={1}>男孩</Radio>
                    <Radio value={0}>女孩</Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item>
                  <Input.Group compact>
                    <Form.Item name={['model', 'sdB3']} label="-3SD" rules={[{ required: true }]}>
                      <InputNumber />
                    </Form.Item>
                    <Form.Item name={['model', 'sdB2']} label="-2SD" rules={[{ required: true }]}>
                      <InputNumber />
                    </Form.Item>
                    <Form.Item name={['model', 'sdB1']} label="-1SD" rules={[{ required: true }]}>
                      <InputNumber />
                    </Form.Item>
                    <Form.Item name={['model', 'sd']} label="SD" rules={[{ required: true }]}>
                      <InputNumber />
                    </Form.Item>
                    <Form.Item name={['model', 'sD1']} label="+1SD" rules={[{ required: true }]}>
                      <InputNumber />
                    </Form.Item>
                    <Form.Item name={['model', 'sD2']} label="+2SD" rules={[{ required: true }]}>
                      <InputNumber />
                    </Form.Item>
                    <Form.Item name={['model', 'sD3']} label="+3SD" rules={[{ required: true }]}>
                      <InputNumber />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>

                <Form.Item>
                  <Space>
                    <Button type="primary" htmlType="submit" loading={loading2}>
                      保存
                    </Button>
                    <Button onClick={this.ResetForm}>新建</Button>
                    <Button onClick={this.CopyData} type="primary">
                      复制
                    </Button>
                    <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                      删除
                    </Button>
                  </Space>
                </Form.Item>
              </Form>
            </Card>
          </Col>
          <Col span={12}></Col>
        </Row>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
